<template>
  <div id="app">
    <div id="nav">
      <div>
        <router-link to="/home">实例页1</router-link> |
        <router-link to="/about">实例页2</router-link>
      </div>
    </div>
    <transition :name="transitionName">
      <router-view></router-view>
    </transition>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //路由切换动画样式
      transitionName: "slide-left",
      //路由记录
      pathList: [],
    };
  },
  watch: {
    $route(to, from) {
      console.log(from.path);
      if (this.pathList.includes(to.path)) {
        const index = this.pathList.findIndex(() => {
          return from.path;
        });
        this.pathList.splice(index, 1);
        // console.log(index);
        this.$router.isBack = true;
      } else {
        this.pathList.push(to.path);
        this.$router.isBack = false;
      }
      if (to.path === "/home") {
        // 'index'为首页
        this.$router.isBack = true;
        this.pathList = [];
      }
      let isBack = this.$router.isBack;
      // console.log(isBack);
      // console.log(this.pathList);
      if (isBack) {
        this.transitionName = "slide-left";
      } else {
        this.transitionName = "slide-right";
      }

      this.$router.isBack = false;
    },
  },
};
</script>

<style>
#app {
  padding: 10px;
}
#nav {
  height: 50px;
  line-height: 50px;
  text-align: center;
  position: fixed;
  width: 100%;
  margin-top: -50px;
  margin-left: -10px;
  transition: all 0.3s linear;
  z-index: 9999;
}
 #nav div{
    height: 40px;
    line-height: 40px;
    background: #00ffd8;
  }
#nav a {
    font-weight: bold;
    color: #2c3e50;
  }
#nav a.router-link-exact-active {
      color: #42b983;
    }
#nav:hover {
  margin-top: -10px;
}
.slide-left-enter-active,
.slide-right-enter-active {
  position: absolute;
  top: 20px;
  width: 97%;
  transition: all 0.8s ease;
}
.slide-left-leave-active,
.slide-right-leave-active {
  transition: all 0.8s ease;
}
.slide-left-enter,
.slide-right-leave-to {
  transform: translateX(100%);
  opacity: 0;
}
.slide-left-leave-to,
.slide-right-enter {
  transform: translateX(-100%);
  opacity: 0;
}
</style>
